import React, { Component } from 'react'
import intl from 'react-intl-universal'
import { Dropdown } from 'react-bootstrap'
import { withRouter } from 'react-router-dom'
import './Language.less'

class Language extends Component {
  constructor () {
    const { currentLocale } = intl.getInitOptions()
    super()
    this.state = {
      currentLocale
    }
  }

  handleChangeLanguage = (eventKey, event) => {
    const { history } = this.props
    // 这里使用localStorage的方式来改变语言环境 因为使用url的话 会改变url 感觉不是很好
    window.localStorage.setItem('lang', eventKey)
    this.setState({
      currentLocale: eventKey
    })
    // 刷新页面 这样刷新页面就相当于按f5  必须要刷新页面不然不会切换语言
    history.go(0)
  }
  switchLocale = () => {
    switch (this.state.currentLocale) {
      case 'zh-CN':
        return '中文简体'
      case 'en-US':
        return 'English'
      default:
    }
  }

  render () {
    const { currentLocale } = this.state
    return (
      <Dropdown>
        <Dropdown.Toggle>{this.switchLocale()}</Dropdown.Toggle>
        <Dropdown.Menu flip = {true}>
          <Dropdown.Item active = {currentLocale === 'zh-CN'}
                         eventKey = {'zh-CN'}
                         onSelect = {this.handleChangeLanguage}>中文(简体)</Dropdown.Item>
          <Dropdown.Item active = {currentLocale === 'en-US'}
                         eventKey = {'en-US'}
                         onSelect = {this.handleChangeLanguage}>English(US)</Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>
    )
  }
}

export default withRouter(Language)
